Shell Script to Read File
Brief: This example will help you to read a file in a bash script. This tutorial contains two methods to read a file line by line using a shell script.
Method 1 – Using simple loop
You can use while read loop to read a file content line by line and store into a variable.
1 2 3 4 5 6 7 8 9 10 11 12 | #!/bin/bash # A shell script to read file line by line filename="/var/log/xyz.log" while read line do # $line variable contains current line read from the file # display $line text on the screen or do something with it. echo "$line" done < $filename |
Note – In above script line is a variable only. You can use any variable name in place of the line of your choice.
Method 2 – Using IFS
The IFS (Internal Field Separator) is a special shell variable used for splitting words and line based on its value. The default value is
1 2 3 4 5 6 7 8 9 10 11 12 | #!/bin/bash # A shell script to read file line by line filename="/var/log/xyz.log" while IFS= read -r line do # $line variable contains current line read from the file # display $line text on the screen or do something with it. echo "$line" done < $filename |